<template>
  <!-- 角色检查加载动画 -->
  <div v-if="roleCheckLoading" class="role-check-loading">
    <el-icon class="is-loading" :size="50" color="#409eff">
      <Loading />
    </el-icon>
    <p class="loading-text">正在加载...</p>
  </div>
  
  <!-- 权限控制：超级管理员和入退审批员无权限查看 -->
  <div v-else-if="currentUserRole === '超级管理员' || currentUserRole === '入退审批员'" class="error-page-container">
    <div class="no-permission-content">
        <div class="permission-icon">
          <el-icon size="80" color="#f56c6c">
            <Lock />
          </el-icon>
        </div>
        <h2 class="permission-title">您无权限查看</h2>
        <p class="permission-desc">抱歉，您当前的权限不足以访问此页面</p>
        <el-button type="primary" @click="goBack" style="width: 100px;">返回</el-button>
      </div>
  </div>

  <!-- 正常页面内容 -->
  <div v-else class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据编号" prop="bussniessId">
        <el-input v-model="queryParams.bussniessId" placeholder="请输入单据编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- 新增单据类别下拉框 -->
      <el-form-item label="单据类别" prop="type" style="margin-left: 20px;">
        <el-select v-model="queryParams.type" placeholder="请选择单据类别" clearable @change="handleQuery"
          style="width: 180px;">
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime" style="margin-left: 20px;">
        <el-date-picker clearable v-model="queryParams.createTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item style="margin-left: 20px;">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>

      <br>

      <!-- 新增流程状态标签和发起申请按钮 -->
      <el-form-item prop="handleType" class="status-form-item">
        <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
          <div class="status-tags-container">
            <div class="status-tags">
              <el-tag
                v-for="item in statusOptions"
                :key="item.value"
               
               :class="['status-tag', queryParams.handleType === item.value ? 'is-dark' : 'is-plain']"
                @click="handleStatusClick(item.value)"
              >
                {{ item.label }}
              </el-tag>
            </div>
          </div>
          <el-button type="primary" @click="showDialog = true" style="width: 130px;">
            发起申请
          </el-button>
        </div>
      </el-form-item>
    </el-form>
    <!-- 自定义弹窗 -->
    <el-dialog v-model="showDialog" title="选择申请单据类别" width="40%">
      <div class="dialog-content">
        <div><span style="color: red">*</span>单据类别：</div>
        <div class="radio-group">
          <label class="radio-item">
            <img
              src="https://www.keaitupian.cn/cjpic/frombd/0/253/2457883294/3501078662.jpg"
              alt="入住图标" />
            <el-radio v-model="form.billType" label="入住"></el-radio>
          </label>
          <label class="radio-item">
            <img
              src="https://ts2.tc.mm.bing.net/th/id/OIP-C.0OAd5thNqbRA43Rk7ZqoIAHaIS?rs=1&pid=ImgDetMain&o=7&rm=3"
              alt="退住图标" />
            <el-radio v-model="form.billType" label="退住"></el-radio>
          </label>
          <label class="radio-item">
            <img
              src="https://ts3.tc.mm.bing.net/th/id/OIP-C.imGL6aUl-XEgXnuNcry_lQHaHb?rs=1&pid=ImgDetMain&o=7&rm=3"
              alt="请假图标" />
            <el-radio v-model="form.billType" label="请假"></el-radio>
          </label>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmDialog">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 表格内容保持不变 -->
    <el-table v-loading="loading" :data="accraditationrecordList" @selection-change="handleSelectionChange">
      <!-- 表格列定义保持不变 -->
      <el-table-column label="序号" align="center" width="100">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="单据编号" align="center" prop="bussniessId" />
      <el-table-column label="单据标题" align="center" prop="currentStep" />
      <el-table-column label="单据类别" align="center" prop="type" />
      <el-table-column label="审批人" align="center" prop="approverName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" align="center" prop="finishTime" width="180">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.finishTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="流程状态" align="center" prop="handleType">
        <template #default="scope">
          <span :class="{
            'status-done': scope.row.handleType == '已审批',
            'status-applying': scope.row.handleType == '申请中',
            'status-closed': scope.row.handleType == '已拒绝',
          }">
            {{ scope.row.handleType }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- 撤销按钮：仅申请中可点击，其他状态禁用且灰色 -->
          <el-button 
            link 
            type="primary" 
            @click="handleDelete(scope.row)" 
            v-hasPermi="['accraditationrecord:accraditationrecord:remove']"
            :disabled="scope.row.handleType !== '申请中'"  
            :class="{ 'btn-disabled': scope.row.handleType !== '申请中' }" 
          >
            撤销
          </el-button>
          <el-button link type="primary" v-hasPermi="['accraditationrecord:accraditationrecord:edit']"
            @click="handleCheck(scope.row)">
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
  </div>
</template>
<script setup name="Accraditationrecord">
import {
  listAccraditationrecord1,
  getAccraditationrecord,
  delAccraditationrecord,
} from "@/api/accraditationrecord/accraditationrecord";
import { getCurrentInstance } from "vue";
import { getRuzhuByElder } from "@/api/rutui/ruzhu";
import { ElMessage } from "element-plus";
import { Loading } from "@element-plus/icons-vue";
import { ref, reactive, toRefs, onMounted } from "vue";
import { useRouter } from "vue-router";
import useUserStore from "@/store/modules/user";
import { getUser } from "@/api/system/user";
const router = useRouter();
const elderlyId = ref(null);
const stepNo = ref(null);
const { proxy } = getCurrentInstance();
const showDialog = ref(false);
const form = ref({
  billType: "",
});

// 用户角色相关
const userStore = useUserStore();
const currentUserRole = ref('');

// 获取用户角色
const fetchUserRole = async () => {
  try {
    const response = await getUser(userStore.id);
    if (response.code === 200) {
      currentUserRole.value = response.data.roles[0].roleName || '';
    }
  } catch (error) {
    console.error('获取用户角色失败：', error);
  }
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

/** 删除按钮操作（新增二次校验：仅申请中可撤销） */
function handleDelete(row) {
  // 二次校验：非申请中数据直接提示，不执行后续逻辑
  if (row.handleType !== '申请中') {
    ElMessage.warning('仅申请中的单据可撤销');
    return;
  }

  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认撤销该申请？').then(function() {
    return delAccraditationrecord(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("撤销成功")
  }).catch(() => {})
}

const confirmDialog = async () => {
  if (!form.value.billType) {
    ElMessage.warning("请选择单据类别");
    return;
  }

  try {
    // 记录当前组件路径
    sessionStorage.setItem(
      "lastComponentPath",
      "/togetherwork/togetherwork1/myapply"
    );

    // 根据选择的单据类型，跳转到不同的页面
    switch (form.value.billType) {
      case "入住":
        await router.push("/togetherwork/togetherwork1/checkappeoval");
        break;
      case "退住":
        await router.push("/togetherwork/togetherwork1/dropappeoval");
        break;
      case "请假":
        await router.push("/togetherwork/togetherwork1/leaveappeoval");
        break;
      default:
        // 理论上不会触发，因为已经通过 radio 限制了选项
        ElMessage.warning("未知的单据类型");
        return;
    }

    // 跳转成功后关闭弹窗
    showDialog.value = false;
  } catch (error) {
    console.error("路由跳转失败，具体错误：", error);
    ElMessage.error("跳转失败，请检查页面组件是否存在");
  }
};

// 定义单据类别选项
const typeOptions = ref([
  // 根据实际业务场景修改选项值
  { label: "请假", value: "请假" },
  { label: "入住", value: "入住" },
  { label: "退住", value: "退住" },
]);

// 审核状态选项（根据表格中注释的状态定义）
const statusOptions = ref([
  { label: "已审批", value: "已审批" },
  { label: "申请中", value: "申请中" },
  { label: "已拒绝", value: "已拒绝" },
]);

// 统一的查看处理函数，根据单据类别调用不同函数
function handleCheck(row) {
  const type = row.type; // 获取当前行的单据类别
  switch (type) {
    case "入住":
      checkCheckIn(row); // 调用入住查看函数
      break;
    case "请假":
      checkLeave(row); // 调用请假查看函数
      break;
    case "退住":
      checkCheckOut(row); // 调用退住查看函数
      break;
    default:
      ElMessage.warning(`未支持的单据类别：${type}`);
  }
}

// 1. 入住单据查看函数（原有的check函数，保留并明确命名）
function checkCheckIn(row) {
  elderlyId.value = row.checkContentId;
  console.log("入住单据 - 传递的elderlyId:", elderlyId.value);
  console.log("当前流程状态:", row.handleType); // 打印状态，便于调试

  // 先判断流程状态是否为“已拒绝”
  if (row.handleType === "已拒绝") {
    // 状态为已拒绝时，跳转到拒绝详情页面
    router.push({
      path: "/togetherwork/togetherwork1/checkreject",
      query: { 
        stepNum: row.stepNo, // 参数名与props的stepNum一致
        elderlyId: elderlyId.value, // 参数名与props的elderlyId一致
        opinion: row.opinion, // 传递审批意见
        approveStatus: row.auditStatus, // 传递审批状态
      }
    });
  } else if (row.stepNo === -1) {
    // 先调用接口，在回调中处理跳转（确保res可用）
    getRuzhuByElder(elderlyId.value).then((res) => {
      console.log("入住单据 - 传递的ruzhuId:", res.data.id);
      
      // 跳转逻辑必须放在then回调内部
      router.push({
        path: "/rutui/ruzhu/checkdetail",
        query: { 
          id: res.data.id, // 此时res已定义，可正确获取id
        }
      });
    }).catch(err => {
      // 增加错误处理，避免接口失败导致页面无响应
      console.error("获取入住单据失败：", err);
      ElMessage.error("数据加载失败，请重试");
    });
  } else if (row.stepNo === 3) {
    // 步骤为3时，跳转至对应详情页面
    router.push({
      path: "/togetherwork/togetherwork1/commonstep3",
      query: { 
        id: row.checkContentId, // 参数名与props的elderlyId一致
      }
    });
  } else if (row.stepNo === 4) {
    // 步骤为4时，跳转至对应详情页面
    router.push({
      path: "/togetherwork/togetherwork1/commonstep4",
      query: { 
        id: row.checkContentId, // 参数名与props的elderlyId一致
      }
    });
  } else if (row.stepNo === 5) {
    // 步骤为5时，跳转至对应详情页面
    router.push({
      path: "/togetherwork/togetherwork1/commonstep5",
      query: { 
        id: row.checkContentId, // 参数名与props的elderlyId一致
      }
    });
  }
}

// 2. 请假单据查看函数（新增）
function checkLeave(row) {
  // 请假单据的参数传递逻辑（根据实际需求调整路径和参数）
  console.log("请假单据 - 查看详情:", row);
  if (row.handleType === "已审批"){
    router.push({
      path: "/togetherwork/togetherwork1/leavecomponents/leave3",
      query: { 
        leaveId:row.leaveContentId,
        stepNum: row.stepNo, // 参数名与props的stepNum一致
        // elderlyId: elderlyId.value, // 参数名与props的elderlyId一致
        opinion: row.opinion, // 传递审批意见
        approveStatus: row.auditStatus, // 传递审批状态
      }
    });
  }else{
    router.push({
    path: "/togetherwork/togetherwork1/leaveappeoval", // 请假详情页面路径
    query: { leaveId: row.leaveContentId, stepNo: row.stepNo }, // 假设用leaveContentId
  });
  }
  
}

// 3. 退住单据查看函数（新增）
function checkCheckOut(row) {
  // 退住单据的参数传递逻辑（根据实际需求调整路径和参数）
  console.log("退住单据 - 查看详情:", row.createTime);
  router.push({
    path: "/togetherwork/togetherwork1/dropappeoval", 
    query: { id: row.dropContentId, stepNum: row.stepNo }, 
  });  
  console.log("退住id"+row.dropContentId+"流程步骤"+row.stepNo);
}

// 表格数据相关
const accraditationrecordList = ref([]);
const loading = ref(true);
const roleCheckLoading = ref(true); // 添加角色检查加载状态
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 响应式数据定义
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    opinion: null,
    type: null,
    finishTime: null,
    approverId: null,
    approverName: null,
    approverNameRole: null,
    nextApproverId: null,
    nextApprover: null,
    nextApproverRole: null,
    bussniessId: null,
    currentStep: null,
    nextStep: null,
    auditStatus: null,
    stepNo: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    handleType: null,
    checkContentId: null,
    dropContentId: null,
    leaveContentId: null,
  },
  rules: {},
});

const { queryParams, rules } = toRefs(data);

/** 查询审批记录列表 */
function getList() {
  loading.value = true;
  listAccraditationrecord1(queryParams.value).then((response) => {
    accraditationrecordList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 处理标签点击 */
function handleStatusClick(value) {
  // 如果点击的是已选中的标签，则取消选中
  if (queryParams.value.handleType === value) {
    queryParams.value.handleType = null;
  } else {
    queryParams.value.handleType = value;
  }
  handleQuery();
}

/** 获取标签类型 */
function getTagType(value) {
  // 改为黑白灰配色，不使用彩色
  return 'info';
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 页面加载时获取用户角色
onMounted(async () => {
  await fetchUserRole();
  
  // 角色检查完成，关闭加载动画
  roleCheckLoading.value = false;
  
  // 只有在有权限的情况下才加载列表
  if (currentUserRole.value !== '超级管理员' && currentUserRole.value !== '入退审批员') {
    getList();
  }
});
</script>

<style scoped>
/* 角色检查加载动画样式 */
.role-check-loading {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 80vh;
  background-color: #ffffff;
}

.loading-text {
  margin-top: 20px;
  color: #606266;
  font-size: 16px;
}

/* 弹窗样式 */
.dialog-content {
  padding: 10px;
}

.radio-group {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
}

.radio-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.radio-item img {
  width: 80px;
  height: 80px;
  margin-top: 10px;
  border-radius: 50%;
  margin-bottom: 10px;
}

/* 流程状态标签样式 */
:deep(.status-done) {
  background-color: white;
  color: #67c23a;
  padding: 2px 6px;
  border-radius: 4px;
  border: 1px solid #67c23a;
}

:deep(.status-applying) {
  background-color: white;
  color: #f59f00;
  padding: 2px 6px;
  border-radius: 4px;
  border: 1px solid #f59f00;
}

:deep(.status-closed) {
  background-color: white;
  color: #f56c6c;
  padding: 2px 6px;
  border-radius: 4px;
  border: 1px solid #f56c6c;
}

/* 新增：禁用状态的撤销按钮样式（灰色且无交互） */
:deep(.btn-disabled) {
  color: #c0c4cc !important; /* 灰色文字 */
  cursor: not-allowed !important; /* 禁用鼠标样式 */
  pointer-events: auto !important; /* 确保禁用状态生效 */
}

/* 取消禁用按钮的hover效果 */
:deep(.btn-disabled:hover) {
  color: #c0c4cc !important;
  text-decoration: none !important; /* 去除hover下划线 */
}

/* 404错误页面样式 */
.error-page-container {
  min-height: calc(100vh - 84px);
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
}

.error-page-content {
  text-align: center;
  padding: 80px 60px;
  border-radius: 8px;
  min-width: 500px;
  min-height: 300px;
}

.error-404 {
  font-size: 100px;
  font-weight: bold;
  color: #909399;
  line-height: 1;
  margin-bottom: 20px;
  font-family: 'Arial', sans-serif;
}

.error-title {
  font-size: 24px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 20px;
}

/* 状态表单项 */
.status-form-item {
  width: 100%;
}

/* 状态标签容器 - 统一背景 */
/* 状态标签容器 - 统一背景 */
.status-tags-container {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 3px 2px;
  display: inline-block;
}

/* 状态标签样式 - 必须用:deep()穿透scoped，否则样式不生效 */
:deep(.status-tags) {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

/* 未选中标签样式 */
:deep(.status-tag) {
  cursor: pointer;
  transition: all 0.3s;
  user-select: none;
  color: #606266;
  border: 1px solid #dcdfe6;
  background-color: #ffffff;
  font-size: 12px;
  padding: 8px 20px;
  height: auto;
  line-height: 1.5;
}

:deep(.status-tag):hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
}

/* 选中标签样式（重点：穿透后才能覆盖默认样式） */
:deep(.status-tag.is-dark) {
  color: #ffffff !important; /* !important确保优先级高于Element Plus默认样式 */
  background-color: #409EFF !important;
  border-color: #e0e0e0 !important;
}

/* 未选中标签样式（确保plain状态生效） */
:deep(.status-tag.is-plain) {
  color: #606266 !important;
  background-color: #ffffff !important;
  border-color: #dcdfe6 !important;
}
/* 无权限页面样式 */
.no-permission-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 80vh;
  background-color: #f8f9fa;
}

.no-permission-content {
  text-align: center;
  padding: 40px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  max-width: 500px;
  width: 100%;
}

.permission-icon {
  margin-bottom: 24px;
}

.permission-title {
  color: #f56c6c;
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 16px 0;
}

.permission-desc {
  color: #666;
  font-size: 16px;
  margin: 0 0 32px 0;
  line-height: 1.5;
}
</style>